package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileSystemView;

import com.jidesoft.swing.JideButton;
import com.jidesoft.swing.JideSplitButton;

import backend.ProgramLauncher;
import backend.XMLCommunicator;

/**
 * This class is the button used. It has an internal method for getting the icon
 * from the path.
 * 
 * @author Itai Raccah
 * 
 */
public class ShortcutButtonEditor extends JideSplitButton implements Shortcut,
		ActionListener {
	private String execPath;
	private String group;
	private String id;

	public ShortcutButtonEditor() {
		super();

	}

	public void setup(String id, String execPath, String displayTitle, String group) {
		this.id = id;
		this.execPath = execPath;
		this.group = group;
		this.setIcon(getShortcutIcon());
		this.setText(displayTitle);
		this.addActionListener(this);
		this.setFocusable(false);
		this.add(new AbstractAction("Remove") {
			public void actionPerformed(ActionEvent e) {
				removeButton();
			}
		});
		this.add(new AbstractAction("Rename") {
			public void actionPerformed(ActionEvent e) {
				renameButton();
			}
		});

	}

	private Icon getShortcutIcon() {
		File file = new File(execPath);
		try {
			Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file);
			return icon;
		} catch (Exception e) {
			return null;
		}

	}

	public void actionPerformed(ActionEvent event) {
		ProgramLauncher.launch(execPath);
	}

	public String getExecPath() {
		return execPath;
	}

	public AbstractButton getComponent() {
		return this;
	}

	private void removeButton() {
		int returnValue = JOptionPane.showConfirmDialog(XMLConfig.getXMLConfig(),
				"This will delete the actual shortcut file, are you sure?", "Remove button",
				JOptionPane.OK_CANCEL_OPTION);
		if (returnValue == JOptionPane.OK_OPTION) {
			XMLConfig.getXMLConfig().getOuterPanel().remove(this);
			XMLCommunicator com = new XMLCommunicator();
			com.removeShortcut(this.id);
			XMLConfig.getXMLConfig().repaint();
			XMLConfig.getXMLConfig().validate();
		}
	}

	private void renameButton() {
		String returnValue = JOptionPane.showInputDialog(this, "Rename to?",
				this.getText());
		if (returnValue != null) {
			XMLCommunicator com = new XMLCommunicator();
			com.renameShortcut(this.id, returnValue);
			this.setText(returnValue);
			XMLConfig.getXMLConfig().repaint();
			XMLConfig.getXMLConfig().validate();
		}
	}

}
